package cn.signalpha.modules.pay.controller;

import cn.signalpha.common.annotation.FormRepeatCommitAnnotation;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.modules.com.entity.UserBank;
import cn.signalpha.modules.com.service.UserBankService;
import cn.signalpha.modules.pay.dto.SignDTO;
import cn.signalpha.modules.pay.dto.SignSmsDTO;
import cn.signalpha.modules.pay.enums.PayTypeEnum;
import cn.signalpha.modules.pay.granter.JoinPayFastGranter;
import cn.signalpha.modules.pay.provider.IPayGranter;
import cn.signalpha.modules.pay.provider.PayGranterBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;


@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_PAY_NAME)
@Api(value = "银行卡签约", tags = "银行卡签约")
public class SignController extends BaseController {

	private final UserBankService userBankService;

	@PostMapping("/sign/sms")
	@FormRepeatCommitAnnotation
	@ApiOperation(value = "发送签约短信")
	public R signSms(@Valid @RequestBody SignSmsDTO signSmsDTO)  {
		IPayGranter payGranter = PayGranterBuilder.getGranter(PayTypeEnum.JOIN_PAY_FAST.getType());
		JoinPayFastGranter joinPayFastGranter = (JoinPayFastGranter) payGranter;
		String orderNo = joinPayFastGranter.signSms(signSmsDTO);
		//把用户签约信息存入缓存
		UserBank userBank = Objects.requireNonNull(BeanUtil.copy(signSmsDTO, UserBank.class));
		userBank.setUserId(getUser().getUserId());
		userBankService.putUserBankCache(userBank.getUserId(), userBank);
		return R.data(orderNo);
	}

	@PostMapping("/sign")
	@FormRepeatCommitAnnotation
	@ApiOperation(value = "进行短信签约")
	public R signSms(@Valid @RequestBody SignDTO signDTO)  {
		IPayGranter payGranter = PayGranterBuilder.getGranter(PayTypeEnum.JOIN_PAY_FAST.getType());
		JoinPayFastGranter joinPayFastGranter = (JoinPayFastGranter) payGranter;
		if(joinPayFastGranter.sign(signDTO)){
			//保存用户的银行卡
			UserBank userBank = userBankService.getUserBankCache(getUser().getUserId());
			userBankService.save(userBank);
		}
		return R.status(true);
	}

}
